//TODO: LeetCode144. 二叉树的前序遍历

//* Ver1 递归
class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> v;
        _preorderTraversal(root, v);
        return v;
    }

    void _preorderTraversal(TreeNode* root, vector<int>& v)
    {
        if (root == nullptr) return;

        v.push_back(root->val);
        _preorderTraversal(root->left, v);
        _preorderTraversal(root->right, v);
    }
};

//* Ver2 迭代
class Solution {
public:
    vector<int> preorderTraversal(TreeNode* root) {
        vector<int> ret;
        stack<TreeNode*> stk;

        TreeNode* cur = root;
        while (cur || !stk.empty()) {
            //先将树的左路节点入栈
            while (cur) {
                ret.push_back(cur->val);
                stk.push(cur);
                cur = cur->left;
            }

            //将树的左路节点遍历完后，依此访问栈中左路节点的右树
            //而右树又可以看作左路节点和右树，就这么循环下去
            //非递归可以看作在模拟进程地址空间的栈帧

            TreeNode* top = stk.top();
            stk.pop();

            //访问左路节点的右树
            cur = top->right;
        }

        return ret;
    }
};